Directives Which Wraps Elements Via Transclusion

Course- AngularJS >

The examples we have seen so far all set the content of the element matching the directive themselves, either via JavaScript code or an HTML template. But what if you wanted a directive to wrap elements inserted into the directive body by the developer? For instance:

<mytransclude>This is a transcluded directive {{firstName}}</mytransclude>

The directive is marked by the <mytransclude> element. But the content inside it is set by the developer. Thus, this part of the HTML should not be replaced by the directive's HTML template. We actually want that part of the HTML to be processed by AngularJS. This processing is called "transclusion".

In order to make AngularJS process the HTML inside a directive, you have to set the transclude property of the directive definition object to true. You will also have to tell AngularJS what part of the directive's HTML template that is to contain the transcluded HTML. You do so by inserting the ng-transclude attribute (a directive, really) into the HTML element in the HTML template where you want the transcluded HTML inserted.

Here is an AngularJS directive that shows how to use transclusion:

<mytransclude>This is a transcluded directive {{firstName}}</mytransclude>

<script>
    myapp = angular.module("myapp", []);
    myapp.directive('mytransclude', function() {
        var directive = {};

        directive.restrict = 'E'; /* restrict this directive to elements */
        directive.transclude = true;
        directive.template = "<div class='myTransclude' ng-transclude></div>";

        return directive;
    });
    myapp.controller("MyController", function($scope, $http) {
        $scope.firstName = "Jakob";
    });
</script>

Notice the HTML inside the <mytransclude> element. This HTML code contains the interpolation directive {{firstName}}. We want AngularJS to process this HTML for us so that interpolation directive is executed. To achieve that I have set the transclude property to true on the directive definition object. I have also inserted an ng-transclude attribute into the HTML template. This attribute tells AngularJS what element to insert the transcluded HTML into.